//
//  ViewController.m
//  二维码扫描DIY
//
//  Created by ning on 16/1/14.
//  Copyright © 2016年 JohnRay. All rights reserved.
//

#import "QRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "Base64+DES.h"
#import "EMCDDeviceManager.h"

#import "USDetailsTableViewController.h"
#import "USFriendDetailController.h"
#import "USWebViewController.h"
#import "USQRcodeLoginController.h"

#import "USCustomMenu.h"

// 延时 delay(10, ^{  });
#define delay(delay, dispatch_block_t) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), dispatch_block_t);


#define VIEW_WIDTH self.view.frame.size.width
#define VIEW_HEIGHT self.view.frame.size.height

static const CGFloat kBorderW = 100;
static const CGFloat kMargin = 30;

@interface QRCodeViewController () <AVCaptureMetadataOutputObjectsDelegate, USCustomMenuDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) UIView *scanWindow;
@property (nonatomic, strong) UIImageView *scanNetImageView;

@property (nonatomic, strong) USCustomMenu *menu;
@end

@implementation QRCodeViewController
{
    UIView *bgMaskView;
    UIActivityIndicatorView * indicator;
}
#pragma mark - 💖 生命周期 (Lifecycle)
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.view addSubview:indicator];
    [indicator startAnimating];
    delay(0.2, ^{
        [indicator stopAnimating];
        [indicator removeFromSuperview];
        [self resumeAnimation];
        [_session startRunning];
    })
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_scanNetImageView.layer removeAllAnimations];
    [_session stopRunning];
}


-(void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title = USLocalizedString(@"二维码");
    indicator = [[UIActivityIndicatorView alloc] init];
    indicator.center = self.view.center;
    indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [indicator startAnimating];
    [self.view addSubview:indicator];
    [self setupMaskView];
    [self setupTipTitleView];
    [self setupScanWindowView];
    delay(0.2, ^{
        [indicator stopAnimating];
        [indicator removeFromSuperview];
        [self beginScanning];
    })
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"left_filled"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = back;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_add_normal"] style:UIBarButtonItemStylePlain target:self action:@selector(showList:)];
    self.navigationItem.rightBarButtonItem = addBtn;
    
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - menu method
/**
 *  展开菜单
 */
- (void)showList:(UIBarButtonItem *)barButtonItem{
    __weak __typeof(self) weakSelf = self;
    if (!self.menu) {
        CGFloat pointX = kUSScreenWidth - 180;
        self.menu = [[USCustomMenu alloc] initWithDataArr:@[USLocalizedString(@"从相册取图片")] origin:CGPointMake(pointX, 64) width:160 rowHeight:kUSButtonHeight];
        _menu.delegate = self;
        _menu.dismiss = ^() {
            weakSelf.menu = nil;
        };
        _menu.arrImgName = @[@"pro_img_normal"];
        [self.view addSubview:_menu];
    } else {
        [_menu dismissWithCompletion:^(USCustomMenu *object) {
            weakSelf.menu = nil;
        }];
    }
    
}

- (void)usCustomMenu:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [imagePickerController.navigationBar setTintColor:[UIColor whiteColor]];
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
        }];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (image == nil) {
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    [picker dismissViewControllerAnimated:YES completion:^{
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }];
    
    // 识别图片
    NSString *content = @"" ;
    NSData *imageData = UIImagePNGRepresentation(image);
    CIImage *ciImage = [CIImage imageWithData:imageData];
    
    //创建探测器
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
    NSArray *feature = [detector featuresInImage:ciImage];
    
    //取出探测到的数据
    for (CIQRCodeFeature *result in feature) {
        content = result.messageString;
    }
    
    
    //copy来的
    // http://192.168.0.190:8080/scanqrcode.action?u=E0GT0c35v9s=
    
    
    NSURL *url = [NSURL URLWithString:content];
    USLog(@"%@ ",url);
    
    NSString *userid =  __TEXT([url.query substringFromIndex:2]);
    
    if ([self isInt:userid]) {
        // 收到消息时，震动
        [[EMCDDeviceManager sharedInstance] playVibration];
        [_session stopRunning];
        NSString *myUserid = [USUserManager sharedUserManager].userid;
        if ([userid isEqualToString:myUserid]) {
            USDetailsTableViewController *detail = [[USDetailsTableViewController alloc]init];
            
            NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
            [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:detail];
            [self.navigationController setViewControllers:vcArray.copy animated:YES];
            
        } else {
            NSString *dataPath = [[USFunction getDocumentPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"Database%@.db",myUserid]];
            
            FMDatabase *db = [FMDatabase databaseWithPath:dataPath];
            if (![db open]) {
                USLog(@"Could not open db");
                return;
            }
            
            NSString *query = [NSString stringWithFormat:@"SELECT count(userid) FROM PersonList WHERE userid = %@ and virtualmark = 0",userid];
            NSString *rs = [db stringForQuery:query];
            [db close];
            if ([rs intValue] == 0) {
                USFriendDetailController *wait = [[USFriendDetailController alloc]init];
                wait.isWaitAddFriend = YES;
                wait.userid = userid;
                
                NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
                [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:wait];
                [self.navigationController setViewControllers:vcArray.copy animated:YES];
                
            }else{
                USFriendDetailController *friendDetail = [[USFriendDetailController alloc]init];
                friendDetail.userid = userid;
                
                NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
                [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:friendDetail];
                [self.navigationController setViewControllers:vcArray.copy animated:YES];
            }
        }
    } else if ([url.query hasPrefix:@"skey="]) {
        [[EMCDDeviceManager sharedInstance] playVibration];
        [_session stopRunning];
        //跳转优售登录
        NSString *skey = [url.query substringFromIndex:5];
        USQRcodeLoginController *login = [USQRcodeLoginController new];
        login.skey = skey;
        
        NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
        [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:login];
        [self.navigationController setViewControllers:vcArray.copy animated:YES];
    } else if ([USFunction isURL:content]) {
        [[EMCDDeviceManager sharedInstance] playVibration];
        [_session stopRunning];
        //网页跳转
        USWebViewController *webView = [USWebViewController new];
        webView.requestURL = url;
        
        NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
        [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:webView];
        [self.navigationController setViewControllers:vcArray.copy animated:YES];
        
        [_session stopRunning];
    } else {
        [SVProgressHUD showInfoWithStatus:USLocalizedString(@"照片中未识别到二维码")];
    }
}



#pragma mark - 💛 自定义方法
- (void)setupMaskView {
    bgMaskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_WIDTH)];
    bgMaskView.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7].CGColor;
    bgMaskView.layer.borderWidth = kMargin ;
    bgMaskView.center = self.view.center;
    [self.view addSubview: bgMaskView];
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, (VIEW_HEIGHT - bgMaskView.frame.size.height) / 2 )];
    topView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    topView.tag = 1001;
    [self.view addSubview: topView];
    
    UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(bgMaskView.frame), VIEW_WIDTH, VIEW_HEIGHT - CGRectGetMaxY(bgMaskView.frame))];
    downView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    [self.view addSubview: downView];
}

-(void)setupTipTitleView{
    UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(bgMaskView.frame) + 20, VIEW_WIDTH, kBorderW)];
    tipLabel.text = USLocalizedString(@"将取景框对准二维码，即可自动扫描");
    tipLabel.textColor = [UIColor whiteColor];
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.lineBreakMode = NSLineBreakByWordWrapping;
    tipLabel.numberOfLines = 2;
    tipLabel.font=[UIFont systemFontOfSize:16];
    tipLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tipLabel];
}

- (void)resumeAnimation {
    CAAnimation *anmitation = [_scanNetImageView.layer animationForKey:@"translationAnimation"];
    if(anmitation){
        [_scanNetImageView.layer setSpeed:1.0];
    } else {
        CGFloat scanNetImageViewH = 241;
        CGFloat scanWindowH = VIEW_WIDTH - kMargin * 2;
        CGFloat scanNetImageViewW = _scanWindow.frame.size.width;
        _scanNetImageView.frame = CGRectMake(0, -scanNetImageViewH, scanNetImageViewW, scanNetImageViewH);
        CABasicAnimation *scanNetAnimation = [CABasicAnimation animation];
        scanNetAnimation.keyPath = @"transform.translation.y";
        scanNetAnimation.byValue = @(scanWindowH);
        scanNetAnimation.duration = 2.0;
        scanNetAnimation.repeatCount = MAXFLOAT;
        [_scanNetImageView.layer addAnimation:scanNetAnimation forKey:@"translationAnimation"];
        [_scanWindow addSubview:_scanNetImageView];
    }
}

- (void)setupScanWindowView {
    CGFloat scanWindowW = VIEW_WIDTH - kMargin * 2;
    _scanWindow = [[UIView alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMinY(bgMaskView.frame) + kMargin, scanWindowW, scanWindowW)];
    _scanWindow.clipsToBounds = YES;
    //_scanWindow.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:_scanWindow];
    _scanNetImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"scan_net"]];
    CGFloat buttonWH = 18;
    NSArray *imageArray = @[@"scan_left1",@"scan_right1",@"scan_left2",@"scan_right2"];
    for (NSInteger i = 0; i < imageArray.count; i++) {
        UIImageView *cornerRadius = [[UIImageView alloc] initWithFrame:CGRectMake((i % 2) == 0 ? 0 : scanWindowW - buttonWH, i > 1 ? scanWindowW - buttonWH + 1 : 0, buttonWH, buttonWH)];
        cornerRadius.image = [UIImage imageNamed:imageArray[i]];
        [_scanWindow addSubview:cornerRadius];
    }
}

- (void)beginScanning {
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    if (!input) {
        return;
    }
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    //[output setMetadataObjectsDelegate:self queue:dispatch_queue_create("liveScanProcQueue", NULL)];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    CGRect frame = _scanWindow.frame;
    
    output.rectOfInterest = CGRectMake(CGRectGetMinY(frame) / VIEW_HEIGHT - 0.05, CGRectGetMinX(frame) / VIEW_WIDTH, frame.size.height / VIEW_HEIGHT + 0.05, frame.size.width / VIEW_WIDTH);
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    [_session addInput:input];
    [_session addOutput:output];
    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    [_session startRunning];
}

// MARK: - 💜 AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            // http://192.168.0.190:8080/scanqrcode.action?u=E0GT0c35v9s=
            
            NSString *urlStr = [metadataObj stringValue];
            NSURL *url = [NSURL URLWithString:urlStr];
            USLog(@"%@ ",url);
            
            NSString *userid =  __TEXT([url.query substringFromIndex:2]);
            
            if ([self isInt:userid]) {
                // 收到消息时，震动
                [[EMCDDeviceManager sharedInstance] playVibration];
                [_session stopRunning];
                NSString *myUserid = [USUserManager sharedUserManager].userid;
                if ([userid isEqualToString:myUserid]) {
                    USDetailsTableViewController *detail = [[USDetailsTableViewController alloc]init];
                    
                    NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
                    [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:detail];
                    [self.navigationController setViewControllers:vcArray.copy animated:YES];
                    
                }else{
                    NSString *dataPath = [[USFunction getDocumentPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"Database%@.db",myUserid]];
                    
                    FMDatabase *db = [FMDatabase databaseWithPath:dataPath];
                    if (![db open]) {
                        USLog(@"Could not open db");
                        return;
                    }
                    
                    NSString *query = [NSString stringWithFormat:@"SELECT count(userid) FROM PersonList WHERE userid = %@ and virtualmark = 0",userid];
                    NSString *rs = [db stringForQuery:query];
                    [db close];
                    if ([rs intValue] == 0) {
                        USFriendDetailController *wait = [[USFriendDetailController alloc]init];
                        wait.isWaitAddFriend = YES;
                        wait.userid = userid;
                        
                        NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
                        [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:wait];
                        [self.navigationController setViewControllers:vcArray.copy animated:YES];
                        
                    }else{
                        USFriendDetailController *friendDetail = [[USFriendDetailController alloc]init];
                        friendDetail.userid = userid;
                        
                        NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
                        [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:friendDetail];
                        [self.navigationController setViewControllers:vcArray.copy animated:YES];
                    }
                }
            }else if ([url.query hasPrefix:@"skey="]){
                [[EMCDDeviceManager sharedInstance] playVibration];
                [_session stopRunning];
                //跳转优售登录
                NSString *skey = [url.query substringFromIndex:5];
                USQRcodeLoginController *login = [USQRcodeLoginController new];
                login.skey = skey;
                
                NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
                [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:login];
                [self.navigationController setViewControllers:vcArray.copy animated:YES];
            }
            else if ([USFunction isURL:urlStr]){
                [[EMCDDeviceManager sharedInstance] playVibration];
                [_session stopRunning];
                //网页跳转
                USWebViewController *webView = [USWebViewController new];
                webView.requestURL = url;
                
                NSMutableArray *vcArray = self.navigationController.viewControllers.mutableCopy;
                [vcArray replaceObjectAtIndex:vcArray.count - 1 withObject:webView];
                [self.navigationController setViewControllers:vcArray.copy animated:YES];
                
                [_session stopRunning];
            }
            
            
        }
    }
    
}
- (BOOL)isInt:(NSString *)string{
    NSScanner *scan = [NSScanner scannerWithString:string];
    int value;
    return [scan scanInt:&value] && [scan isAtEnd];
}

@end
